import Taro from "@tarojs/taro"
import { useCouponStore } from "@/common/hox/couponStore"
import { useDynamicList, useRequest } from "ahooks"
import dayjs from "dayjs"
import { Decimal } from "decimal.js"
import { createGlobalStore } from "hox"
import { useCallback, useEffect, useMemo, useState } from "react"
import { getMovieCinemaInfo } from "@/service"
import { getUserBenefitCardList } from "@/service"
import { getSeatPrice } from "../utils"
import { useAppSettingStore } from "@/common/hox/appSettingStore"
import { TicketModeEnum } from '@/utils/enum'

export const [useMovieStore, getMovieStore] = createGlobalStore(() => {
  // 组合权益信息
  const [combinationInfo, setCombinationInfo] = useState<Combination.Item>()
  const getCouponBatchApi = useRequest((_couponCode: string) => getUserBenefitCardList({
    filterType: getUserBenefitCardList.filterEnum.unUse
  }), {
    manual: true,
    onSuccess: (res, params) => {
      const list = res.list || []
      const couponInfo = list.find(item => item.couponCode === params[0])
      if (!couponInfo) return setCombinationInfo(undefined)
      const { totalNum, usedNum } = couponInfo
      const unUsed = totalNum - usedNum
      setCombinationInfo(unUsed ? couponInfo : undefined)
    },
  })

  // 影院信息
  const [cinemaInfo, setCinemaInfo] = useState<Movie.CinemaItem>()
  const getMovieCinemaInfoApi = useRequest(getMovieCinemaInfo, {
    manual: true,
    onSuccess: data => data && setCinemaInfo(data)
  })

  // 电影信息
  const [movieDetail, setMovieDetail] = useState<Movie.CinemaMovieItem>()

  // 优惠券信息 仅用于查看，不用于数据选取 后续考虑从store中移除
  const { movieCouponList, refreshCoupon } = useCouponStore()
  const couponList = useMemo(() => {
    if (!movieCouponList || !movieDetail) return []
    if (combinationInfo) return []
    return movieCouponList.filter(item => {
      if (!item.productIds.length) return true
      return item.productIds.find(i => i === movieDetail.id)
    })
  }, [movieCouponList, movieDetail, !!combinationInfo])
  const hasCoupon = useMemo(() => couponList.length > 0, [couponList])


  // 当前选中优惠券
  const [selectCoupon, setSelectCoupon] = useState<Coupon.ListItem>()

  // 场次信息
  const [scheduleDetail, setScheduleDetail] = useState<Movie.TheaterItem>()

  // 场次座位基本信息
  const [scheduleSeatInfo, setScheduleSeatInfo] = useState<Omit<Movie.CinemaScheduleSeat, 'isvFilmSeatData' | 'isvFilmSeatAreaPriceData'>>()

  // 购票模式
  const [issueTicketMode, setIssueTicketMode] = useState<0 | 1>()

  // 是否允许调座
  const [acceptChangeSeat, setAcceptChangeSeat] = useState(false)
  useEffect(() => { if (scheduleSeatInfo) setAcceptChangeSeat(false) }, [scheduleSeatInfo])



  // 座位信息
  const seatDynamicList = useDynamicList<Movie.IsvFilmSeatDatum>()
  const handleClickSeats = useCallback((list: Movie.IsvFilmSeatDatum[] = []) => {
    const seatIds = list.map(item => item.seatId)
    const isRemove = !!seatDynamicList.list.find(item => seatIds.includes(item.seatId))
    if (isRemove) {
      seatDynamicList.resetList(seatDynamicList.list.filter(item => !seatIds.includes(item.seatId)))
    } else {
      const selectSeat = seatDynamicList.list
      const firstSeatItem = selectSeat[0]
      if (firstSeatItem) {
        const { officialPrice } = firstSeatItem
        if (list.find(item => item.officialPrice !== officialPrice)) {
          return Taro.showToast({
            title: '只能选择相同价位的座位',
            icon: 'none'
          })
        }
      }
      let unUsed = 4
      if (combinationInfo) {
        const { totalNum, usedNum, singleUseLimit } = combinationInfo
        unUsed = Math.min(totalNum - usedNum, singleUseLimit)
      }
      if (selectSeat.length + list.length > unUsed) {
        return Taro.showToast({
          title: combinationInfo
            ? `权益卡最多允许选${unUsed}个座位`
            : `本场次最多允许售卖${unUsed}张票`,
          icon: "none"
        })
      }
      list.forEach(item => seatDynamicList.push(item))
    }
  }, [seatDynamicList, combinationInfo])

  const appConfig = useAppSettingStore()
  // 开场前40分钟 特惠购票不可用 
  const specialModeDisabled = useMemo(() => Boolean(scheduleDetail && dayjs(scheduleDetail.showTime).diff(new Date(), 'minute') < 45), [scheduleDetail])
  // 默认购票模式
  useEffect(() => {
    const ticketMode = appConfig.ticketMode
    if (ticketMode.length === 1) {
      setIssueTicketMode(ticketMode[0])
      return
    }
    // 票券优惠模式
    const couponTicketMode = (function () {
      if (combinationInfo) return combinationInfo.issueTicketMode
      if (selectCoupon) return selectCoupon.issueTicketMode
      return undefined
    })()
    // 非票券优惠模式
    const normalTicketMode = (function () {
      if (!seatDynamicList.list.length || !scheduleDetail) return
      // 取第一个座位价格为标准
      const { fastPrice, specialPrice } = seatDynamicList.list[0]
      return fastPrice > specialPrice ? TicketModeEnum.SlowTicket : TicketModeEnum.FastTicket
    })()
    if (couponTicketMode !== undefined) return setIssueTicketMode(couponTicketMode)
    if (specialModeDisabled) return setIssueTicketMode(TicketModeEnum.FastTicket)
    if (normalTicketMode !== undefined) return setIssueTicketMode(normalTicketMode)
    return setIssueTicketMode(TicketModeEnum.FastTicket)
  }, [seatDynamicList.list, scheduleDetail, selectCoupon, specialModeDisabled, combinationInfo, appConfig.ticketMode])

  // 座位价格
  const seatTotalPrice = useMemo(() => {
    const defaultPrice = {
      totalSellPrice: 0,
      totalOfficialPrice: 0,
      seatItemPrice: 0
    }
    if (!seatDynamicList.list.length) return { ...defaultPrice, totalReducePrice: 0 }
    let seatItemPrice = 0;
    const { totalSellPrice, totalOfficialPrice } = seatDynamicList.list.reduce((priceData, item) => {
      const { totalSellPrice, totalOfficialPrice } = priceData
      const seatPriceData = getSeatPrice(item, hasCoupon)
      new Decimal(totalSellPrice).plus(new Decimal(seatPriceData.sellPrice)).toNumber()
      seatItemPrice = new Decimal(seatPriceData.officialPrice).mul(new Decimal((selectCoupon?.conversionQuantity || 1))).toNumber();
      return {
        //originPrice
        totalSellPrice: new Decimal(totalSellPrice).plus(new Decimal(seatPriceData.sellPrice)).toNumber(),
        // totalSellPrice: new Decimal(totalSellPrice).plus(new Decimal(seatPriceData.sellPrice)).toNumber(),
        totalOfficialPrice: new Decimal(totalOfficialPrice).plus(new Decimal(seatPriceData.officialPrice)).toNumber(),
        // totalOfficialPrice: new Decimal(totalOfficialPrice).plus(new Decimal(seatPriceData.officialPrice)).toNumber(),
      }
    }, defaultPrice)
    return {
      totalSellPrice,
      totalOfficialPrice,
      totalReducePrice: new Decimal(totalOfficialPrice).sub(new Decimal(totalSellPrice)).toNumber(),
      seatItemPrice
    }
  }, [seatDynamicList.list, hasCoupon, !!combinationInfo, selectCoupon])

  // 支付金额
  const paymentAmount = useMemo(() => {
    if (combinationInfo) return 0
    let sellPriceValue = 0;
    const totalSellPrice = seatDynamicList.list.reduce((price, item) => {
      // 默认售价取实际是否使用优惠券为判断标准
      const { sellPrice } = getSeatPrice(item, !!selectCoupon)
      const { fastPrice } = item
      sellPriceValue = sellPrice;
      // 求和的时候判断当前购票模式，0为原价，1为售价
      return new Decimal(price).plus(new Decimal(issueTicketMode === 0 ? fastPrice : sellPrice)).toNumber()
    }, 0)
    if (selectCoupon) return Math.max(Decimal.sub(totalSellPrice, selectCoupon.couponType === 1 ? new Decimal(sellPriceValue).mul(new Decimal((selectCoupon?.conversionQuantity || 1))).toNumber() : selectCoupon.batchValue).toNumber(), 0)
    return totalSellPrice
  }, [seatDynamicList.list, selectCoupon, issueTicketMode, combinationInfo, selectCoupon])

  const refreshCouponInfo = useCallback(() => {
    if (combinationInfo) {
      getCouponBatchApi.run(combinationInfo.couponCode)
    } else setCombinationInfo(undefined)
    refreshCoupon()
  }, [combinationInfo])

  return {
    refreshCouponInfo,
    cinema: {
      // 影院信息
      cinemaInfo,
      setCinemaInfo,
      fetchCinema: getMovieCinemaInfoApi.runAsync,
    },
    combination: {
      // 组合权益信息
      combinationInfo,
      setCombinationInfo,
      reloadCombinationInfo: getCouponBatchApi.run,
    },
    coupon: {
      // 优惠券信息
      refreshCoupon,
      // 用户电影拥有优惠券列表
      couponList,
      // 用户电影是否拥有优惠券 couponList.length > 0
      hasCoupon,
      // 选中的优惠券
      selectCoupon,
      setSelectCoupon
    },
    movie: {
      // 电影详情
      movieDetail,
      setMovieDetail
    },
    schedule: {
      // 影院场次信息
      scheduleDetail,
      setScheduleDetail,
      // 场次座位基本信息
      scheduleSeatInfo,
      setScheduleSeatInfo,
      // 是否调座
      acceptChangeSeat,
      setAcceptChangeSeat,
      // 购票模式
      issueTicketMode,
      setIssueTicketMode,
      // 特惠购票是否禁用
      specialModeDisabled,
    },
    seat: {
      // 座位信息
      seatList: seatDynamicList.list,
      // 重置选座
      seatReset: () => {
        seatDynamicList.resetList([])
        setSelectCoupon(undefined)
      },
      // 座位点击
      handleClickSeats,
      // 选座总价
      seatTotalPrice,
    },
    paymentAmount,
  }
})